
#include <BFont>
#include <BPainter>
#include <BTextEdit>
#include <BLayout>

#include "OperaStackWidget.h"

OperaStackWidget::OperaStackWidget(BWidget* parent) : BTableWidget("Opera-Stack", parent)
{
	this->setTitleVisible(false);
	this->setGridStyle(Grid_Horizontal);

	this->setColumnCount(4);
	this->setColumnLabel(0, "name");
	this->setColumnLabel(1, "line");
	this->setColumnLabel(2, "index");
	this->setColumnLabel(3, "text");

	_textEdit = 0;

	connect(this, Signal_AssetChanged, &OperaStackWidget::slotAssetChanged);
}
OperaStackWidget::~OperaStackWidget()
{

}

void OperaStackWidget::freshOperaList()
{
	this->clearItems();
	bool dark = false;
	BReal time = 0;
	for (int i = 0; i < _textEdit->operaCount(); i++)
	{
		const BOpera* opera = _textEdit->opera(i);
		if (time == 0)
			time = opera->time;
		else if (time != opera->time)
			dark = !dark;
		BString text;
		switch (opera->mode)
		{
		case BOpera::Mode_Input:
			text << "input";
			break;
		case BOpera::Mode_Insert:
			text << "insert";
			break;
		case BOpera::Mode_Remove:
			text << "remove";
			break;
		case BOpera::Mode_Delete:
			text << "delete";
			break;
		default:
			break;
		}
		this->addItem(i, 0, text);
		this->addItem(i, 1, opera->line);
		this->addItem(i, 2, opera->index);
		this->addItem(i, 3, opera->text);
		this->setRowLabel(i, i);
		this->setRowAsset(i, opera);
		if (dark)
			this->setRowColor(i, BColor(200, 210, 220));
	}
}

void OperaStackWidget::slotAssetChanged(BObject* object, const BValue& value)
{
	BTextEdit* textEdit = value;
	if (_textEdit != textEdit)
	{
		if (_textEdit)
		{
			disconnect(_textEdit);
			this->clearItems();
		}
		_textEdit = textEdit;
		if (_textEdit)
		{
			connect(_textEdit, Signal_Opera, &OperaStackWidget::slotTextEditOpera);
			freshOperaList();
		}
	}
}
void OperaStackWidget::slotTextEditOpera(BTextEdit* textEdit, const BValue& value)
{
	freshOperaList();
}

void OperaStackWidget::paintEvent(const BEvent& event)
{
	BTableWidget::paintEvent(event);
	if (_textEdit)
	{
		int operaIndex = _textEdit->operaIndex();
		BPainter painter(this);
		const BFont* font = painter.realFont();
		BRect leftRect = this->rect(Part_Left);
		if (BTableItem* item = this->item(operaIndex))
		{
			BRect rect = item->rect();
			rect.left() = leftRect.right() - 10;
			rect.right() = leftRect.right();
			rect.bottom() = rect.top() + 4;
			rect.top() -= 4;
			rect.move(2, 0);

			painter.setPolySmooth(true);
			painter.setColor(200, 0, 0);
			painter.drawGraph(rect, Graph_Arrow_Right_Fill);
		}
		else
		{
			BRect area = this->area();
			BRect rect;
			rect.left() = leftRect.right() - 10;
			rect.right() = leftRect.right();
			rect.top() = area.bottom() - 4;
			rect.bottom() = area.bottom() + 4;
			rect.move(2, 0);

			painter.setPolySmooth(true);
			painter.setColor(200, 0, 0);
			painter.drawGraph(rect, Graph_Arrow_Right_Fill);
		}
	}
}
